/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.os.rh.telas;

import br.os.rh.curso.Curso;
import br.os.rh.curso.CursoDAO;
import br.os.rh.periodo.Periodo;
import br.os.rh.periodo.PeriodoDAO;
import br.os.rh.salario.Salario;
import br.os.rh.salario.SalarioDAO;
import br.os.rh.util.Calculo;
import br.os.rh.util.ConnectionFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

/**
 *
 * @author Pedro Saraiva
 */
public class TelaGeraPlanilhaFolhaProfessores extends javax.swing.JDialog {

    /**
     * Creates new form TelaRelatorioAcervo
     */
    public TelaGeraPlanilhaFolhaProfessores() {
        initComponents();
        setModal(true);
        setLocationRelativeTo(null);
        preenchePeriodo();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btSair = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        Descricao_Biblioteca = new javax.swing.JLabel();
        cbPeriodo = new javax.swing.JComboBox();
        btImprimir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Relatório Acervo");
        setModal(true);
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setPreferredSize(new java.awt.Dimension(432, 177));

        btSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/os/rh/imagens/SA.png"))); // NOI18N
        btSair.setToolTipText("Sair");
        btSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSairActionPerformed(evt);
            }
        });

        jPanel3.setBackground(new java.awt.Color(153, 204, 255));
        jPanel3.setLayout(null);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel5.setText("PLANILHA SALÁRIO PROFESSORES");
        jPanel3.add(jLabel5);
        jLabel5.setBounds(0, 10, 280, 17);

        Descricao_Biblioteca.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N
        Descricao_Biblioteca.setText("Período.: *");

        cbPeriodo.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N
        cbPeriodo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--" }));
        cbPeriodo.setToolTipText("Informe o Período");

        btImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/os/rh/imagens/imprimir2.png"))); // NOI18N
        btImprimir.setToolTipText("Sair");
        btImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btImprimirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btImprimir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btSair))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(Descricao_Biblioteca)
                        .addComponent(cbPeriodo, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(25, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(Descricao_Biblioteca, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbPeriodo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btSair)
                    .addComponent(btImprimir))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        getAccessibleContext().setAccessibleName("Planilha Salário Professores");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSairActionPerformed
        dispose();
    }//GEN-LAST:event_btSairActionPerformed

    private void btImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btImprimirActionPerformed
        // TODO add your handling code here:
        if (cbPeriodo.getSelectedIndex() > 0) {
            SalarioDAO dao = new SalarioDAO();
            List<Salario> salarios = dao.pesquisaPeriodo((Periodo) cbPeriodo.getSelectedItem());
            Collections.sort(salarios);
            try {
                if (salarios.size() > 0) {
                    geraPlanilha(salarios);
                    JOptionPane.showMessageDialog(rootPane, "Planilha gerada com sucesso!");
                } else {
                    JOptionPane.showMessageDialog(rootPane, "Não existem dados para gerar!!");
                }

            } catch (IOException ex) {
                JOptionPane.showMessageDialog(rootPane, "ERRO: " + ex.getMessage());
            }

        } else {
            JOptionPane.showMessageDialog(rootPane, "Informe o período!");
        }


    }//GEN-LAST:event_btImprimirActionPerformed

    public void geraPlanilha(List<Salario> lista) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet1 = wb.createSheet("Professores");

        HSSFCellStyle estilo = wb.createCellStyle();
        //Adicionando bordas
        estilo.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        estilo.setBottomBorderColor(HSSFColor.BLACK.index);
        estilo.setBorderTop(HSSFCellStyle.BORDER_THIN);
        estilo.setTopBorderColor(HSSFColor.BLACK.index);
        estilo.setBorderRight(HSSFCellStyle.BORDER_THIN);
        estilo.setRightBorderColor(HSSFColor.BLACK.index);
        estilo.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        estilo.setLeftBorderColor(HSSFColor.BLACK.index);
        HSSFRow row = sheet1.createRow(0);
        row.createCell(0).setCellValue("Nome");
        row.createCell(1).setCellValue("Titulação");
        row.createCell(2).setCellValue("Curso");
        row.createCell(3).setCellValue("Cidade");
        row.createCell(4).setCellValue("Horas");
        row.createCell(5).setCellValue("Valor Hora Aula");
        row.createCell(6).setCellValue("Valor Horista");
        row.createCell(7).setCellValue("Valor Mensalista");
        row.createCell(8).setCellValue("1 Sexto");
        row.createCell(9).setCellValue("Gratificação");
        row.createCell(10).setCellValue("Ajuda de Custo");
        row.createCell(11).setCellValue("Comissão");
        row.createCell(12).setCellValue("Total");
//        row.createCell(12).setCellValue("Adiantamentos");
//        row.createCell(13).setCellValue("Descontos");
        for (int j = 0; j < 12; j++) {
            row.getCell(j).setCellStyle(estilo);
        }
        double valorGeral = 0;

        for (int i = 0; i < lista.size(); i++) {
            Salario s = lista.get(i);
            if (s.isProfessor() && s.getFuncionario().isAtivo()) {
                row = sheet1.createRow(i + 1);

                row.createCell(0).setCellValue(s.getFuncionario().getNome());
                row.createCell(1).setCellValue(s.getFuncionario().getTitulacao().getDescricao());
//                row.createCell(2).setCellValue(s.getDisciplinas().get(0).getDisciplina().getSemestre().getCurso().getSigla());
                row.createCell(3).setCellValue(s.getFuncionario().getCidade().getDescricao());
//                row.createCell(4).setCellValue((Calculo.calculoHorasSemestre(s.getDisciplinas())*20));
                row.createCell(5).setCellValue(s.getValHoraAula());

//                double valorMensalHorista = (((Calculo.calculoHorasSemestre(s.getDisciplinas())) *4.5)) * s.getValHoraAula();
//                row.createCell(6).setCellValue(valorMensalHorista);
//                row.createCell(7).setCellValue(s.getSalario());
//                double umSexto = valorMensalHorista / 6;
//                row.createCell(8).setCellValue(umSexto);
//                double gratificacao = Calculo.calculoGratificacaoHorista(s.getPorcentGratifica(), valorMensalHorista+s.getSalario());
//                row.createCell(9).setCellValue(gratificacao);
//                row.createCell(10).setCellValue(s.getValAjudaCusto());
//                row.createCell(11).setCellValue(s.getComissao());
//                double total = Calculo.calculoHorista(s.getDisciplinas(), s.getValHoraAula(),
//                        s.getValAjudaCusto(), s.getPorcentGratifica(), s.getHorasMensalista(), s.getSalario(), s.getComissao());
//                row.createCell(12).setCellValue(total);
//                valorGeral += total;

//                row.createCell(12).setCellValue("adiantamentos");
//                row.createCell(13).setCellValue("desconto");
                for (int j = 0; j < 12; j++) {
                    row.getCell(j).setCellStyle(estilo);
                }

            }

        }

        row = sheet1.createRow(row.getRowNum() + 1);

        row.createCell(12).setCellValue(valorGeral);
//        row.createCell(11).setCellStyle(estilo);

        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showDialog(this, "Salvar");
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            System.out.println(file.getPath());
            FileOutputStream stream = new FileOutputStream(file.getPath() + ".xls");
            wb.write(stream);
        } else {
            JOptionPane.showMessageDialog(rootPane, "Operação Cancelada!");
        }

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaGeraPlanilhaFolhaProfessores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaGeraPlanilhaFolhaProfessores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaGeraPlanilhaFolhaProfessores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaGeraPlanilhaFolhaProfessores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaGeraPlanilhaFolhaProfessores().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel Descricao_Biblioteca;
    private javax.swing.JButton btImprimir;
    private javax.swing.JButton btSair;
    private javax.swing.JComboBox cbPeriodo;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    // End of variables declaration//GEN-END:variables

    private void preenchePeriodo() {
        PeriodoDAO pDAO = new PeriodoDAO();
        for (int i = 0; i < pDAO.listar().size(); i++) {
            cbPeriodo.addItem(pDAO.listar().get(i));
        }
    }

//    private void preencheCurso() {
//        CursoDAO cDAO = new CursoDAO();
//        for (int i = 0; i < cDAO.listar().size(); i++) {
//            cbCurso.addItem(cDAO.listar().get(i).getDescricao());
//        }
//    }
}
